Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
How do I find the "max" string in Javascript?

Similar to How to sort strings in JavaScript but I want to avoid sorting first, I just want the "largest" value of a string. For example

f(['Aa', 'B', 'C', 'Acd', 'Ace']) == 'C'

I am thinking it's something with .reduce like

const f = (a) => a.reduce(someFunctionGoesHere)

Where some function has an undefined check

UPDATE: Got it working but looks fugly. I wonder if I can reduce that function

const someFunctionGoesHere = (prev, current) => {
  if (!prev) {
    return current;
  }
  else if (prev.localeCompare(current) < 0) {
    return current;
  } else {
    return prev;
  }
};
const f = (a) => a.reduce(someFunctionGoesHere)

console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));

UPDATE: this works, one line, but looks quite ugly. I guess this is the best that can be done with Javascript itself.

const maxString = (a) => a.reduce((prev, current) => (!prev || prev.localeCompare(current) < 0) ? current : prev)

console.log(maxString(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Indeed, reduce() will get you there:

const f = (array) => array.reduce((a, v) => v.localeCompare(a) > 0 ? v : a, '');

console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda